package middleware

import (
	"fmt"
	"net/http"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type AdminAuthMiddleware struct {
	Secret string
}

func NewAdminAuthMiddleware(secret string) *AdminAuthMiddleware {
	return &AdminAuthMiddleware{
		Secret: secret,
	}
}

func (m *AdminAuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 从JWT中获取用户信息
		token := r.Header.Get("Authorization")
		if token == "" {
			httpx.Error(w, jwt.ErrTokenMalformed)
			return
		}

		// 解析token
		claims := jwt.MapClaims{}
		_, err := jwt.ParseWithClaims(token[7:], claims, func(token *jwt.Token) (interface{}, error) {
			return []byte(m.Secret), nil
		})
		if err != nil {
			httpx.Error(w, err)
			return
		}

		// 这里简化处理，实际应该查询数据库验证用户角色
		// 在实际项目中，应该从数据库查询用户信息验证角色
		username := claims["username"].(string)
		if username != "admin" {
			httpx.Error(w, fmt.Errorf("无权访问：需要管理员权限"))
			return
		}

		next(w, r)
	})
}